package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private HttpServletRequest request;

    public boolean isFill() {
        try {
            String requestURI = request.getRequestURI();
            // 如果是来自小程序的请求，不要自动填充创建人和更新人
            if(requestURI.startsWith("/member")) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", Date.class, DateUtils.getNowDate());
        if (isFill()) {
            this.strictInsertFill(metaObject, "createBy", String.class, getLoginUserId());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 默认更新策略是：如果属性有值，则不覆盖
//        this.strictUpdateFill(metaObject, "updateTime", Date.class, DateUtils.getNowDate());
//        this.strictUpdateFill(metaObject, "updateBy", String.class, getLoginUserId());

        // 不论属性有没有值，都覆盖
        this.setFieldValByName("updateTime", DateUtils.getNowDate(), metaObject);
        if (isFill()) {
            this.setFieldValByName("updateBy", getLoginUserId(), metaObject);
        }
    }

    /**
     * 获取当前登录人的id
     * @return  登录人id
     */
    private String getLoginUserId() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (!ObjectUtils.isEmpty(loginUser)) {
                return loginUser.getUserId().toString();
            }
            return "1";
        } catch (Exception e) {
            return "1";
        }
    }
}
